package app.r_teenus.backend.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateAccessor;
import org.springframework.orm.hibernate3.HibernateTemplate;

import app.r_teenus.backend.model.Address;
import app.r_teenus.backend.model.AddressType;
import app.r_teenus.backend.model.Contact;
import app.r_teenus.backend.model.ContactType;
import app.r_teenus.backend.model.SubjectType;


public class DefaultDaoImpl implements DefaultDao {

	public HibernateTemplate hibernateTemplate;

	public void setSessionFactory(SessionFactory sessionFactory) {
		hibernateTemplate = new HibernateTemplate(sessionFactory);
		hibernateTemplate.setFlushMode(HibernateAccessor.FLUSH_AUTO);
	}

	public Address createNewAddress(int id, int subType) {
		Address address = new Address();
		address.setSubject(id);
		address.setSubjectType(subType);
		address.setAllAddressType(findAllAddressType());
		address.setAddressTypeId(address.getAllAddressType().get(0).getId());
		return address;
	}

	public Contact createNewContact(int id, int subType) {
		Contact contact = new Contact();
		contact.setSubject(id);
		contact.setSubjectType(subType);
		contact.setAllContactType(findAllContactType());
		contact.setContactTypeId(contact.getAllContactType().get(0).getId());
		return contact;
	}

	@SuppressWarnings("unchecked")
	public List<Address> findAddress(int id, int subType) {
		Address address = new Address();
		address.setSubject(id);
		address.setSubjectType(subType);
		return hibernateTemplate.findByExample(address);

	}

	@SuppressWarnings("unchecked")
	public List<Contact> findContact(int id, int subType) {
		Contact contact = new Contact();
		contact.setSubject(id);
		contact.setSubjectType(subType);
		return hibernateTemplate.findByExample(contact);
	}

	public Address findAddressById(int id) {
		Address address = hibernateTemplate.get(Address.class, id);
		address.setAddressTypeId(address.getAddressType().getId());
		address.setAllAddressType(findAllAddressType());
		return address;
	}

	public Contact findContactById(int id) {
		Contact contact = hibernateTemplate.get(Contact.class, id);
		contact.setContactTypeId(contact.getContactType().getId());
		contact.setAllContactType(findAllContactType());
		return contact;
	}

	public AddressType findAddressTypeById(int id) {
		return hibernateTemplate.get(AddressType.class, id);
	}

	public ContactType findContactTypeById(int contactTypeId) {
		return hibernateTemplate.get(ContactType.class, contactTypeId);
	}

	public List<ContactType> findAllContactType() {
		return hibernateTemplate.loadAll(ContactType.class);
	}

	public List<AddressType> findAllAddressType() {
		return hibernateTemplate.loadAll(AddressType.class);
	}
	
	public List<SubjectType> findSubjectTypes() {
		return hibernateTemplate.loadAll(SubjectType.class);
	}
}
